
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ScrewTurn.Wiki.PluginFramework;
using System.Text.RegularExpressions;

namespace ScrewTurn.Wiki {

	public partial class Post : BasePage {

		private PageInfo page;
		private PageContent content;

		protected void Page_Load(object sender, EventArgs e) {
			Page.Title = Resources.Messages.PostTitle + " - " + Settings.WikiTitle;

			if(Request["Page"] == null) Response.Redirect(Settings.DefaultPage + Settings.PageExtension);

			page = Pages.Instance.FindPage(Request["Page"]);

			if(page == null) Response.Redirect(Settings.DefaultPage + Settings.PageExtension);

			if(page.Provider.ReadOnly) Response.Redirect(page.Name + Settings.PageExtension);

			content = Content.GetPageContent(page, true);

			switch(Settings.DiscussionPermissions.ToLowerInvariant()) {
				case "page":
					// Check Authorization
					if(SessionFacade.LoginKey != null) {
						// Logged in
						if(page.Status == PageStatus.Locked && !SessionFacade.Admin) {
							// Access denied
							Response.Redirect("AccessDenied.aspx");
						}
					}
					else {
						// Anonymous
						if(Settings.PublicAccess && page.Status != PageStatus.Locked || page.Status == PageStatus.Public) {
							// Allowed
						}
						else {
							// Login required
							Response.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode("Post.aspx?Page=" + Tools.UrlEncode(page.Name) + (Request["Parent"] != null ? "&Parent=" + Request["Parent"] : "")));
						}
					}
					break;
				case "public":
					// Nothing to do
					break;
				case "locked":
					if(SessionFacade.LoginKey == null) Response.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode("Post.aspx?Page=" + Tools.UrlEncode(page.Name) + (Request["Parent"] != null ? "&Parent=" + Request["Parent"] : "")));
					else if(!SessionFacade.Admin) Response.Redirect("AccessDenied.aspx");
					break;
				case "normal":
					if(SessionFacade.LoginKey == null) Response.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode("Post.aspx?Page=" + Tools.UrlEncode(page.Name) + (Request["Parent"] != null ? "&Parent=" + Request["Parent"] : "")));
					break;
			}

			captcha.Visible = SessionFacade.LoginKey == null && !Settings.DisableCaptchaControl;

			if(Page.IsPostBack) return;

			string username = Request.UserHostAddress;
			if(SessionFacade.LoginKey != null) username = SessionFacade.Username;

			lblPostMessage.Text += ": <b>" + content.Title + "</b>";

			bool edit = Request["Edit"] != null;

			if(!edit) {
				lblEdit.Visible = false;

				lblSender.Text += ": <b>" + username + "</b>";

				if(Request["Parent"] != null) {
					try {
						int.Parse(Request["Parent"]);
					}
					catch {
						Response.Redirect(Settings.DefaultPage + Settings.PageExtension);
					}
					List<Message> messages = new List<Message>(Pages.Instance.GetPageMessages(page));
					Message parent = Pages.Instance.FindMessage(messages, int.Parse(Request["Parent"]));

					if(parent != null) {
						lblInReply.Text += ": " + parent.Subject;
						txtSubject.Text = (!parent.Subject.ToLowerInvariant().StartsWith("re:") ? "Re: " : "") + parent.Subject;
					}
					else lblInReply.Visible = false;
				}
				else lblInReply.Visible = false;
			}
			else {
				lblInReply.Visible = false;

				try {
					int.Parse(Request["Edit"]);
				}
				catch {
					Response.Redirect(Settings.DefaultPage + Settings.PageExtension);
				}
				List<Message> messages = new List<Message>(Pages.Instance.GetPageMessages(page));
				Message msg = Pages.Instance.FindMessage(messages, int.Parse(Request["Edit"]));

				if(msg != null) {
					lblEdit.Text += ": <b>" + msg.Subject + "</b>";
					txtSubject.Text = msg.Subject;
					txtBody.Text = msg.Body;
					lblSender.Text += ": <b>" + msg.Username + "</b>";
				}
				else throw new Exception("Message not found (" + page.Name + "." + Request["Edit"] + ").");
			}

		}

		protected void btnSend_Click(object sender, EventArgs e) {
			if(!Page.IsValid || txtBody.Text.Replace(" ", "").Length == 0 || txtSubject.Text.Replace(" ", "").Length == 0) {
				lblResult.CssClass = "resulterror";
				lblResult.Text = Resources.Messages.SubjectAndBodyNeeded;
				return;
			}

			Regex r = new Regex(@"\<script.*?\>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
			if(r.Match(txtBody.Text).Success) {
				lblResult.CssClass = "resulterror";
				lblResult.Text = @"<span style=""color: #FF0000;"">" + Resources.Messages.ScriptDetected + "</span>";
				return;
			}

			string username = Request.UserHostAddress;
			if(SessionFacade.LoginKey != null) username = SessionFacade.Username;

			if(Request["Edit"] == null) {
				int parent = -1;
				try {
					parent = int.Parse(Request["Parent"]);
				}
				catch { }

				Pages.Instance.AddMessage(page, username, txtSubject.Text, DateTime.Now, txtBody.Text, parent);
			}
			else {
				List<Message> messages = new List<Message>(Pages.Instance.GetPageMessages(page));
				Message msg = Pages.Instance.FindMessage(messages, int.Parse(Request["Edit"]));
				Pages.Instance.ModifyMessage(page, int.Parse(Request["Edit"]), msg.Username, txtSubject.Text, DateTime.Now, txtBody.Text);
			}
			Response.Redirect(page.Name + Settings.PageExtension + "?Discuss=1&NoRedirect=1");
		}

		protected void btnCancel_Click(object sender, EventArgs e) {
			Response.Redirect(page.Name + Settings.PageExtension + "?Discuss=1&NoRedirect=1");
		}

		protected void btnPreview_Click(object sender, EventArgs e) {
			lblPreview.Visible = true;
			lblPreview.Text = @"<div id=""PreviewDiv"">" + FormattingPipeline.FormatWithPhase1And2(txtBody.Text, null) + "</div>";
		}

	}

}
